package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-28
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) {
        if(StringUtils.isEmpty(loginDto.getName())||StringUtils.isEmpty(loginDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,loginDto.getName());
        AdUser adUser = this.getOne(queryWrapper);
        if(adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        if (adUser.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        String password = loginDto.getPassword() + adUser.getSalt();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!md5DigestAsHex.equals(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("userId",adUser.getId());
        claimMaps.put("userName",adUser.getName());
        String token = AppJwtUtil.getToken(claimMaps);
        Map<String, Object> map = new HashMap<>();
        //用户信息做脱敏处理
        adUser.setPhone(null);
        adUser.setPassword(null);
        adUser.setEmail(null);
        adUser.setSalt(null);
        map.put("user",adUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
